<?php
/**
 * Created by PhpStorm.
 * User: 秋刀鱼
 * Date: 2018/6/7
 * Time: 9:57
 */

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use yii\db\query;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\web\models;
use \common\helps\tools;//使用工具类
use yii\db\ActiveRecord;
use yii\db\Connection;

/**
 * Site controller
 */
class BudgetController extends Controller
{

    public function init()
    {
        $this->enableCsrfValidation = false;
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {

//        $session = Yii::$app->session;
//        if(empty($session['id'])){
//            $this->redirect(['login/index']);
//        }
        return $this->render('index');
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionReimbursement()
    {
        return $this->render('reim');
    }


    /**
     * @inheritdoc
     */
    public static function getDb()
    {
        return new Connection([
            'dsn' => 'oci:dbname=//localhost:1521/dbname;charset=utf8',
            'username' => 'ydj',
            'password' => 'ydj',
        ]);
    }


    /**
     * title 课题查询
     * Displays homepage.
     *
     * @return string
     */
    public function actionItem()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $id = $post['id'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken($id,$token);
        if($checkToken != 4){
            return tools::ajax_return('2','token过期,请重新登录',[$checkToken]);
        }


        $query = new \yii\db\Query();

//        $org_id = $query
//            ->select(['PHONE'])
//            ->from('D_USER')
//            ->all();
//        $connection  = Yii::$app->db;
//        $sql="SELECT * FROM D_USER";
//        $sql="INSERT into D_USER(id,phone) values('0d521a5e2d364b8d917501a1e1b41f3f','18701626993')";

//        $command = $connection->createCommand($sql);
//        $res     = $command->queryAll();
//        var_dump($org_id);die;




        $org_id = $query
            ->select(['org_id'])
            ->from('ifssc_php.t_s_user_org')
            ->where(['user_id' => $id])
            ->one();
        //部门
        $depart = $query
            ->select(['ID','departname','org_code','org_type'])
            ->from('ifssc_php.t_s_depart')
            ->where(['ID'=>$org_id['org_id']])
            ->one();



        //查上级
        $tree = tools::familyTree($depart,$depart['org_code']);
        $list = array_reverse($tree);//反转

        foreach($list as $k => $v){
            //名称
            switch($v['org_type']){
                case 1:
                    $list[$k]['title_name'] = '机构';
                    break;
                case 2:
                    $list[$k]['title_name'] = '部门';
                    break;
                case 3:
                    $list[$k]['title_name'] = '课题组';
                    break;
                default:
                    $list[$k]['title_name'] = '课题组';
            }

        }

        return tools::ajax_return(0,'成功',$list);
    }



    /**
     * title 报销课题查询
     * Displays homepage.
     *
     * @return string
     */
    public function actionApplyitem()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $id = $post['id'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken($id,$token);
        if($checkToken != 4){
            return tools::ajax_return('2','token过期,请重新登录',[$checkToken]);
        }


        $query = new \yii\db\Query();

        $org_id = $query
            ->select(['org_id'])
            ->from('ifssc_php.t_s_user_org')
            ->where(['user_id' => $id])
            ->one();
        //部门
        $depart = $query
            ->select(['ID','departname','org_code','org_type'])
            ->from('ifssc_php.t_s_depart')
            ->where(['ID'=>$org_id['org_id']])
            ->one();



        //查上级
        $tree = tools::familyTree($depart,$depart['org_code']);
        $list = array_reverse($tree);//反转
        foreach($list as $k => $v){
            //名称
            switch($v['org_type']){
                case 1:
                    $list[$k]['title_name'] = '机构';
                    break;
                case 2:
                    $list[$k]['title_name'] = '部门';
                    break;
                case 3:
                    $list[$k]['title_name'] = '课题组';
                    break;
                default:
                    $list[$k]['title_name'] = '课题组';
            }

        }

        return tools::ajax_return(0,'成功',$list);
//        $org_id = $org_id['org_id'];
//        return $this->render('applyitem',['list'=>$list,'org_id' => $org_id]);
    }


    /**
     * title 报销记录
     * Displays homepage.
     *
     * @return string
     */
    public function actionApply()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $id = $post['id'];
        $token = $post['token'];
        $page = $post['currentPage'];
        $pageSize = $post['pageSize'];
        //token验证
        $checkToken = tools::checkToken($id,$token);
        if($checkToken != 4){
            return tools::ajax_return('2','token过期,请重新登录',[$checkToken]);
        }


        $query = new \yii\db\Query();
        //pc端审核  完成报销
        $local_url = 'http://172.18.80.9:8081';
        $server_url = 'http://159.226.20.75:8081';


        $mdata1 = [];
        $mdata2 = [];
        $ldata = [];
        $b = 1;
        $price = 1000;

        //增值税
        $morevat = $query
            ->select(['id','create_name', 'vatTime','vatJine','budget_type','image','key2'])
            ->from('ifssc_php.vat_ticket')
            ->where(['create_by' => $id])
            ->all();
        if(empty($morevat)){
            return tools::ajax_return_error(0,'成功',[]);
        }
        //筛选超过金额限制
        $morevatArr = [];
        foreach($morevat as $kt => $vt){
            $ticket_vat_k2 = explode('≡', $vt['key2']);
            $vat_price = $ticket_vat_k2[12] != NULL ? $ticket_vat_k2[12] : '0';
            $vt['new_price'] = $vat_price;
            if($vat_price != 0) {
                if ((int)$vat_price > $price) {
                    $morevatArr[] = $vt;
                }
            }
        }


        if(!empty($morevatArr)) {
            foreach ($morevatArr as $v) {
                $ticket_vat_k2 = explode('≡', $v['key2']);
                $vat_price=$ticket_vat_k2[12] != NULL ? $ticket_vat_k2[12] : '0';
                $v['new_price'] = (int)$vat_price;
                $v['fakeOrder'] = tools::fakeOrder('c', $b);
                $v['order'] = $b;
                $v['type_name'] = '增值税票';
                $v['local_url'] = $local_url . $v['image'];
                $v['server_url'] = $server_url . $v['image'];
                if($v['budget_type'] ==3){
                    $mdata2[] = $v;
                }else{
                    $mdata1[] = $v;
                }

                $b++;
            }
        }
        //筛选小于等于金额
        $lessvat = [];
        foreach($morevat as $kt => $vtt){
            $ticket_vat_k2 = explode('≡', $vtt['key2']);
            $vat_price=$ticket_vat_k2[12] != NULL ? $ticket_vat_k2[12] : '0';
            $vtt['new_price'] = $vat_price;
            if($vat_price < $price || ($vat_price = $price)){
                $lessvat[] = $vtt;
            }
        }
        if(!empty($lessvat)) {
            foreach ($lessvat as $vv) {
                $ticket_vat_k2 = explode('≡', $vv['key2']);
                $vat_price=$ticket_vat_k2[12] != NULL ? $ticket_vat_k2[12] : '0';
                $vv['new_price'] = $vat_price;
                $vv['fakeOrder'] = tools::fakeOrder('c', $b);
                $vv['order'] = $b;
                $vv['type_name'] = '增值税票';
                $vv['local_url'] = $local_url . $vv['image'];
                $vv['server_url'] = $server_url . $vv['image'];

                $ldata[] = $vv;
                $b++;
            }
        }
        $list1 = [];
        $list1 = array_merge($mdata1,$mdata2);
        $vdata['list'] = array_merge($list1,$ldata);
//        var_dump($vdata['list']);die;
        $vdata['currentPage'] = $page;

        //总页数
        $vdata['total'] =  ceil(count($vdata['list'])/$pageSize);

        //超过页数
        if($vdata['total'] < ceil($page)){
            return tools::ajax_return(2,'请输入正确页数');
        }
        //页数小于0 或者等于0
        if(ceil($page) < 0 || (ceil($page) == 0)){
            return tools::ajax_return(2,'请输入正确页数');
        }
        //分页
        $startPage = ($page-1)*$pageSize;//起始数据
        $endPage = $page*$pageSize;//结束数据
        $pageList = [];
        foreach($vdata['list'] as $key => $value){
            if(empty($pageSize) || ($pageSize == 1)){
                if($key > 0 || ($key == 0) || ($key < 10)){
                    $pageList[] = $value;
                }

            }else{
                if(($key > $startPage && ($key < $endPage)) || ($key == $startPage) ){
                    $pageList[] = $value;
                }

            }
        }
        $vdata['list'] = $pageList;

        return tools::ajax_return(0,'成功',$vdata);
    }

    /**
     * title 机构条件筛选 人员 课题
     */
    public function actionOrganization(){
        header('Access-Control-Allow-Origin:*');
        $query = new \yii\db\Query();

        $post = Yii::$app->request->post();
        $org_type = $post['org_type'];
        $org_id = $post['org_id'];
        $user_id = $post['user_id'];
        $data = [];
        if($org_type == 4) {
            $row = $query
                ->select(['ID', 'user_id', 'org_id'])
                ->from('ifssc_php.t_s_user_org')
                ->where(['org_id' => $org_id])
                ->all();
//            $departname = '';
//            $org_code = '';
//            $org_type = '';
            foreach ($row as $k => $v) {
                $user = $query
                    ->select(['ID', 'realname'])
                    ->from('ifssc_php.t_s_base_user')
                    ->where(['ID' => $v['user_id']])
                    ->one();

//                $v['uid'] = $v['ID'];
//                $v['$departname'] = $departname;
//                $v['org_code'] = $org_code;
//                $v['org_type'] = $org_type;
                $v['realname'] = $user['realname'];
                $data[] = $v;

            }
        }else{
            $array = ['1f62342a62d180840162d1a6a4d50024','1f62342a62d180840162d1a6a4c00020','1f62342a62d180840162d1a6a4ca0022'];
            //课题
            $row = $query
                ->select(['project_no', 'id', 'project_name'])
                ->from('ifssc_php.project_info')
                ->where(['project_head_id' => $user_id])
                ->andWhere(['not in','id',$array])
                ->all();
            $data = $row;
        }
        //1 机构 2部门 3课题组 4人员 5课题

//            case 1:
//                $row = $query
//                    ->select(['id','departname','org_code','org_type'])
//                    ->from('ifssc_php.t_s_depart')
//                    ->where(['org_type' => $org_type])
//                    ->all();
//                $use_id = '';
//                $org_id = '';
//                $uid = '';
//                foreach($row as $k => $v){
//                    $v['use_id'] = $use_id;
//                    $v['org_id'] = $org_id;
//                    $v['uid'] = $uid;
//                    $data[] = $v;
//
//
//                }
//
//        break;


        $ajax = tools::ajax_return('0','成功',$data);
        return $ajax;

    }


    /**
     * title 课题经费预算及使用情况
     */
    public function actionItemfee()
    {
        header('Access-Control-Allow-Origin:*');
        $query = new \yii\db\Query();

        $post = Yii::$app->request->post();
        $item_id = $post['item_id'];
//        $item_id = '1f62342a62d180840162d1a6a4c00020';
        $data = [];
        $item_info = [];
        $item_info1 = '';
        $row = $query
            ->select(['fee_name','budget_total','buy_total'])
            ->from('ifssc_php.atlas_budget')
            ->where(['item_id' => $item_id,'status' => 1])
            ->all();

        //总额
        $project_info = $query
            ->select(['item_info','budget_total','buy_total'])
            ->from('ifssc_php.project_info')
            ->where(['id' => $item_id])
            ->one();
        foreach($row as  $v){

            $v['all_budget_total'] = bcdiv($project_info['budget_total'] , 10000, 2);
            $v['all_buy_total'] = bcdiv($project_info['buy_total'], 10000, 2);
            $v['buy_total'] = bcdiv($v['buy_total'], 10000, 2);
            $v['budget_total'] = bcdiv($v['budget_total'], 10000, 2);


            $v['item_info'] = $project_info['item_info'];

            $data[] = $v;
        }

        $ajax = tools::ajax_return('0','成功',$data);
        return $ajax;


    }

    /**
     * title 科目查询
     */
    public function actionAtlaselect()
    {
        header('Access-Control-Allow-Origin:*');
        $query = new \yii\db\Query();

        $post = Yii::$app->request->post();
        $item_id = $post['item_id'];
        $row = $query
            ->select(['id','fee_name','budget_total','buy_total'])
            ->from('ifssc_php.atlas_budget')
            ->where(['item_id' => $item_id])
            ->all();

        foreach($row as $k => $v){
            $row[$k]['buy_total'] = tools::tenThousand($v['buy_total']);
            $row[$k]['budget_total'] = tools::tenThousand($v['budget_total']);
        }



        $ajax = tools::ajax_return('0','成功',$row);
        return $ajax;


    }

    /**
     * title 报销 默认费用查询
     */
    public function actionDefaultfee()
    {
        header('Access-Control-Allow-Origin:*');
        $query = new \yii\db\Query();

        $post = Yii::$app->request->post();
        $item_id = $post['item_id'];
        $tid = $post['tid'];


        $data2 = [];
        $row = $query
            ->select(['fee_name','budget_total','buy_total'])
            ->from('ifssc_php.atlas_budget')
            ->where(['item_id' => $item_id,'status' => 1])
            ->all();

        //总额
        $project_info = $query
            ->select(['item_info','budget_total','buy_total','balance_total'])
            ->from('ifssc_php.project_info')
            ->where(['id' => $item_id])
            ->one();
        foreach($row as  $v){

            $v['item_info'] = $project_info['item_info'];

            $v['all_budget_total'] = tools::tenThousand($project_info['budget_total']);
            $v['all_buy_total'] = tools::tenThousand($project_info['buy_total']);
            $v['buy_total'] = tools::tenThousand($v['buy_total']);
            $v['budget_total'] = tools::tenThousand($v['budget_total']);


            $data2[] = $v;
        }
        $data['main'] = $data2;

        //票据信息
        $ticket = $query
            ->select(['vatJine','image','key2'])
            ->from('ifssc_php.vat_ticket')
            ->where(['id' => $tid])
            ->one();
        $local_url = 'http://172.18.80.9:8081';
        $server_url = 'http://159.226.20.75:8081';
        $ticket['image'] = $local_url.$ticket['image'];

        $ticket_vat_k2 = explode('≡', $ticket['key2']);
        $vat_price=!empty($ticket_vat_k2[12]) ? $ticket_vat_k2[12] : '0';
        $ticket['price'] = $vat_price;
        $data['ticket'] = $ticket;
        return tools::ajax_return('0','成功',$data);


    }


    /**
     * title 推荐课题 费用查询
     */
    public function actionAtlasfee()
    {
        header('Access-Control-Allow-Origin:*');
        $query = new \yii\db\Query();
        $post = Yii::$app->request->post();
        $token = $post['token'];
        $item_id = $post['item_id'];
        $user_id = $post['user_id'];
        $uid = $post['uid'];
        $tid = $post['tid'];
        $fee_id = $post['fee_id'];
        $type = $post['type'];
        //token验证
        $checkToken = tools::checkToken($uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('2','token过期,请重新登录',[$checkToken]);
        }
        if(empty($fee_id)){
            return tools::ajax_return('3','请选择费用',[]);
        }

        if(empty($item_id)){
            return tools::ajax_return('3','请选择课题',[]);
        }

        if($type != 1 && $type != 2){
            return tools::ajax_return('3','请传正确type参数',[]);
        }


        $data = [];
        $iData = [];
        $rData = [];


        //票据
        $vat = $query
            ->select(['key2'])
            ->from('ifssc_php.vat_ticket')
            ->where(['id' => $tid])
            ->one();

        if($vat['key2'] != null) {
            $ticket_vat_k2 = explode('≡', $vat['key2']);
            $vat_price=isset($ticket_vat_k2[12]) ? $ticket_vat_k2[12] : '0';

        }else{
            $vat_price = 0;
        }

        $row = $query
            ->select(['id','fee_name','budget_total','buy_total'])
            ->from('ifssc_php.atlas_budget')
            ->where(['item_id' => $item_id,'status' => 1])
            ->all();
        $a_price = '';
        foreach($row as $vr){
            if($vr['id'] == $fee_id){
                $new_price = $vat_price + $vr['buy_total'];
                $a_price = $new_price;
            }else{
                $new_price = 0;
            }
//            var_dump($new_price);die;
            $vr['vat_price'] =  bcdiv($new_price, 10000, 2);
            $vr['budget_total'] = bcdiv($vr['budget_total'], 10000, 2);
            $vr['buy_total'] = bcdiv($vr['buy_total'], 10000, 2);

            $rData[] = $vr;


        }

        $array = ['1f62342a62d180840162d1a6a4d50024','1f62342a62d180840162d1a6a4c00020','1f62342a62d180840162d1a6a4ca0022'];
        //查询本人所有课题
        $item = $query
            ->select(['project_no','project_name','budget_total','buy_total','balance_total'])
            ->from('ifssc_php.project_info')
            ->where(['project_head_id' => $user_id])
            ->andWhere(['not in','id',$array])
            ->orderBy('balance_total DESC')
            ->limit(4)
            ->all();
        foreach($item as $k => $v){
            //超过预算 去掉
            if($v['budget_total'] < $vat_price+$v['buy_total']){
                unset($item[$k]);
            }else {

                $item[$k]['all_budget_total'] = bcdiv($v['budget_total'], 10000, 2);
                $item[$k]['all_buy_total'] = bcdiv($v['buy_total'], 10000, 2);
                $item[$k]['buy_total'] = bcdiv($v['buy_total'], 10000, 2);
                $item[$k]['budget_total'] = bcdiv($v['budget_total'], 10000, 2);

            }

        }

        $data['left'] = $rData;
        $data['right'] = $item;



//        //是否超过余额
//        $atlas_budgets = $query
//            ->select(['id','fee_name','budget_total','buy_total'])
//            ->from('ifssc_php.atlas_budget')
//            ->where(['id' => $fee_id])
//            ->one();
            $sql = "SELECT `id`, `fee_name`, `budget_total`, `buy_total` FROM `ifssc_php`.`atlas_budget` WHERE `id`=" . $fee_id;
            $atlas_budget = Yii::$app->db->createCommand($sql)->queryOne();

//        var_dump($a_price);die;

        if (empty($a_price)) {
                $ajax = tools::ajax_return('1', '成功', $data);
                return $ajax;


        }else{
                if ((int)$atlas_budget['budget_total'] < $a_price) {
                    $ajax = tools::ajax_return('1', '成功', $data);
                    return $ajax;

            }else{
        //总额
        $project_info = $query
            ->select(['item_info','budget_total','buy_total','balance_total'])
            ->from('ifssc_php.project_info')
            ->where(['id' => $item_id])
            ->one();
                $query = new \yii\db\Query();
                //正常报销
                $data = [];
                $data2 = [];

                //票据信息
                $ticket = $query
                    ->select(['vatJine','image','key2'])
                    ->from('ifssc_php.vat_ticket')
                    ->where(['id' => $tid])
                    ->one();
                $local_url = 'http://172.18.80.9:8081';
                $server_url = 'http://159.226.20.75:8081';
                $ticket['image'] = $local_url.$ticket['image'];

                $ticket_vat_k2 = explode('≡', $ticket['key2']);
                $vat_price=!empty($ticket_vat_k2[12]) ? $ticket_vat_k2[12] : '0';
                $ticket['price'] = $vat_price;
                $data['ticket'] = $ticket;

                //修改数据库
                $time = date('Y-m-d H:i:s',time());
                $update_atlas_budget = Yii::$app->db->createCommand()->update('ifssc_php.atlas_budget', ['buy_total' => $a_price,'update_time' => $time], 'id = '.$fee_id)->execute();

                if(!$update_atlas_budget){
                    $ajax = tools::ajax_return('3','失败',[11]);
                    return $ajax;
                }
                //返回前端
                    $row = $query
                        ->select(['fee_name','budget_total','buy_total'])
                        ->from('ifssc_php.atlas_budget')
                        ->where(['item_id' => $item_id,'status' => 1])
                        ->all();


                    foreach($row as  $v){

                        $v['item_info'] = $project_info['item_info'];
                        $v['all_budget_total'] = tools::tenThousand($project_info['budget_total']);
                        $v['all_buy_total'] = tools::tenThousand($project_info['buy_total']);
                        $v['buy_total'] = tools::tenThousand($v['buy_total']);
                        $v['budget_total'] = tools::tenThousand($v['budget_total']);


                        $data2[] = $v;
                    }
                    $data['main'] = $data2;

                $buy_total = $project_info['buy_total'] + $vat_price;
                $balance_total = $project_info['budget_total'] - $buy_total;

                //不能超过总额
                $all_budget = $query->select(['budget_total'])->from('ifssc_php.project_info')->where(['id' => $item_id])->one();
                if($all_budget['budget_total'] < ($buy_total +$balance_total)){
                    return tools::ajax_return_error('3','不能超过总额',[12]);
                }

                $update_atlas_budget = Yii::$app->db->createCommand()->update('ifssc_php.project_info', ['buy_total' => $buy_total,'balance_total' => $balance_total], ['id' => $item_id])->execute();

                if(!$update_atlas_budget){
                    $ajax = tools::ajax_return('3','票据金额不能为0',[13]);
                    return $ajax;
                }
                $update_vat = Yii::$app->db->createCommand()->update('ifssc_php.vat_ticket', ['budget_type' => 3,
                'update_date' => $time], ['id' => $tid])->execute();
                if(!$update_vat){
                    $ajax = tools::ajax_return('3','失败',[14]);
                    return $ajax;
                }

                //添加 科目调整表
                $create_time = date('Y-m-d H:i:s',time());
                $budAdd = new \app\models\Budget;
                $add_id = '';
                $add = $budAdd->budgetAdd($ticket['price'],$fee_id,$add_id,$create_time,1);
                if(!$add){
                    $ajax = tools::ajax_return_error('3','失败',[16]);
                    return $ajax;
                }

                //最新id
                $lastId = Yii::$app->db->getLastInsertId();

                //添加消息列表
                $redis = Yii::$app->cache;
                $accessToken = $redis->get($uid);
                $info = new \app\models\NewInfo;
                $insert = $info->addInfo($uid,$accessToken['realname'],$lastId,$type);
                if(!$insert){
                    $ajax = tools::ajax_return('3','失败',[15]);
                    return $ajax;
                }


                $ajax = tools::ajax_return('2','成功',$data);
                return $ajax;

            }
        }





    }


    /**
     * title 推荐课题
     */
    public function actionAdjustitem(){
        header('Access-Control-Allow-Origin:*');
        $query = new \yii\db\Query();
        $post = Yii::$app->request->post();
        $token = $post['token'];
        $user_id = $post['user_id'];
        $tid = $post['tid'];
        $fee_id = $post['fee_id'];
        //token验证
        $checkToken = tools::checkToken($user_id,$token);
        if($checkToken != 4){
            return tools::ajax_return('2','token过期,请重新登录',[$checkToken]);
        }

        //科目
        $atlas = $query
            ->select(['fee_ids','item_id'])
            ->from('ifssc_php.atlas_budget')
            ->where(['id' => $fee_id])
            ->one();

        //票据
        $vat = $query
            ->select(['key2'])
            ->from('ifssc_php.vat_ticket')
            ->where(['id' => $tid])
            ->one();

        if($vat['key2'] != null) {
            $ticket_vat_k2 = explode('≡', $vat['key2']);
            $vat_price=isset($ticket_vat_k2[12]) ? $ticket_vat_k2[12] : '0';

        }else{
            $vat_price = 0;
        }

        $array = ['1f62342a62d180840162d1a6a4d50024','1f62342a62d180840162d1a6a4c00020','1f62342a62d180840162d1a6a4ca0022'];
        //查询本人所有课题
        $data = [];


        //课题
        $item = $query
            ->select(['id','project_no','project_name','budget_total','buy_total','balance_total'])
            ->from('ifssc_php.project_info')
            ->where(['project_head_id' => $user_id])
            ->andWhere(['not in','id',$array])
            ->andWhere(['<>','id',$atlas['item_id']])
            ->orderBy('balance_total DESC')
            ->limit(4)
            ->all();
//        foreach($item as $k => $v){
//            //超过预算 去掉
//
//            if($v['budget_total'] < $vat_price+$v['buy_total']){
//                unset($item[$k]);
//            }else {
//
//                $item[$k]['all_budget_total'] = bcdiv($v['budget_total'], 10000, 2);
//                $item[$k]['all_buy_total'] = bcdiv($v['buy_total'], 10000, 2);
//                $item[$k]['buy_total'] = bcdiv($v['buy_total'], 10000, 2);
//                $item[$k]['budget_total'] = bcdiv($v['budget_total'], 10000, 2);
//
//            }
//
//        }
        //科目
        $query = new \yii\db\Query();
        $below = [];

        foreach($item as $kk => $vv){
            $atlas_budget = $query->select(['item_id', 'id', 'fee_name', 'budget_total', 'buy_total'])->from('ifssc_php.atlas_budget')->where(['item_id' => $vv['id'], 'fee_ids' => $atlas['fee_ids']])->one();
            if((float)$atlas_budget['budget_total'] < $vat_price+$atlas_budget['buy_total']){
                unset($item[$kk]);
            }else {

                $below['id'] = $atlas_budget['id'];
                $below['fee_name'] = $atlas_budget['fee_name'];

                $below['buy_total'] = bcdiv($atlas_budget['buy_total'], 10000, 2);
                $below['budget_total'] = bcdiv($atlas_budget['budget_total'], 10000, 2);


                $below['item_id'] = $vv['id'];
                $below['project_no'] = $vv['project_no'];
                $below['project_name'] = $vv['project_name'];
                $below['all_budget_total'] = bcdiv($vv['budget_total'], 10000, 2);
                $below['all_buy_total'] = bcdiv($vv['buy_total'], 10000, 2);


            }

            $data[] = $below;
        }
            if(empty($below)){
                return tools::ajax_return('0','成功',[]);
            }


            return tools::ajax_return('0','成功',$data);




    }


    /**
     * title 报销课题费用查询 已不用
     */
    public function actionApplyfee()
    {
        header('Access-Control-Allow-Origin:*');
        $query = new \yii\db\Query();

        $post = Yii::$app->request->post();
        $item_id = $post['item_id'];
        $tid = $post['tid'];
        $data = [];
        $data2 = [];
        $row = $query
            ->select(['fee_name','budget_total','buy_total'])
            ->from('ifssc_php.atlas_budget')
            ->where(['item_id' => $item_id,'status' => 1])
            ->all();

        //总额
        $project_info = $query
            ->select(['item_info','budget_total','buy_total'])
            ->from('ifssc_php.project_info')
            ->where(['id' => $item_id])
            ->one();
        foreach($row as  $v){

            $v['all_budget_total'] = $project_info['budget_total'];
            $v['all_buy_total'] = $project_info['buy_total'];
            $v['item_info'] = $project_info['item_info'];


            $data2[] = $v;
        }
        $data['main'] = $data2;
        //票据信息
        $ticket = $query
            ->select(['vatJine','image'])
            ->from('ifssc_php.vat_ticket')
            ->where(['id' => $tid])
            ->one();
        $local_url = 'http://172.18.80.9:8081';
        $server_url = 'http://159.226.20.75:8081';
        $ticket['image'] = $local_url.$ticket['image'];
        $data['ticket'] = $ticket;


        $ajax = tools::ajax_return('0','成功',$data);
        return $ajax;


    }

    /**
     * title 不予调增科目
     */
    public function actionNoadd(){
        header('Access-Control-Allow-Origin:*');

        $post = Yii::$app->request->post();
        $fee_name = $post['fee_name'];
        $uid = $post['id'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken($uid,$token);
        if($checkToken != 4){
            return tools::ajax_return_error('2','token过期,请重新登录',[$checkToken]);
        }

        //是否不予调增
        $budget = new \app\models\Budget;
        $details = $budget->noAdd();
        foreach($details as $k => $v){
            if($v['name'] == $fee_name){
                $status = 1;
            }
        }


        if($status == 1){
            return tools::ajax_return_error(1,$fee_name.'不予调增',[]);
        }else{
            return tools::ajax_return(0,'成功',[]);
        }


    }


    /**
     * title 推荐方案
     */
    public function actionAdjustfee()
    {
        header('Access-Control-Allow-Origin:*');
//        $connection = new \yii\db\Connection([
//            'dsn'=>'mysql:host=172.18.80.9;dbname=ifssc_api',
//            'username'=>'root',
//            'password'=>'123qwe@@',
//        ]);
//        $connection->open();


        $query = new \yii\db\Query();

        $post = Yii::$app->request->post();
        $tid = $post['tid'];
        $add_id = $post['add_id'];
//        $lower_id = $post['lower_id'];
//        $price = $post['price'];
        $user_id = $post['user_id'];

        //票据
        $vat = $query
            ->select(['key2'])
            ->from('ifssc_php.vat_ticket')
            ->where(['id' => $tid])
            ->one();
        if($vat['key2'] != null) {
            $ticket_vat_k2 = explode('≡', $vat['key2']);
            $vat_price=isset($ticket_vat_k2[12]) ? $ticket_vat_k2[12] : '0';
        }else{
            $vat_price = 0;
        }


        $itemArr = [];
        //调整费用
        $item_id = $query
            ->select(['id','item_id','fee_name','budget_total','buy_total'])
            ->from('ifssc_php.atlas_budget')
            ->where(['id' => $add_id,'status' => 1])
            ->one();

        $atlas_budget = $query
            ->select(['id','item_id','fee_name','budget_total','buy_total'])
            ->from('ifssc_php.atlas_budget')
            ->where(['item_id' => $item_id['item_id'],'status' => 1])
            ->all();
        //是否有不符合条件的科目
        foreach($atlas_budget as $k => $v){
            if((($v['buy_total']+$vat_price) > $v['budget_total']) || (($v['buy_total']+$vat_price) == $v['budget_total'])){
                unset($atlas_budget[$k]);
            }

        }

        //没有调整费用  返回课题推荐
        if(empty($atlas_budget)){


            //查询本人所有课题
            $array = ['1f62342a62d180840162d1a6a4d50024','1f62342a62d180840162d1a6a4c00020','1f62342a62d180840162d1a6a4ca0022'];
            $item = $query
                ->select(['id','project_no','project_name','budget_total','buy_total','balance_total'])
                ->from('ifssc_php.project_info')
                ->where(['project_head_id' => $user_id])
                ->andWhere(['not in','id',$array])
                ->orderBy('balance_total DESC')
                ->limit(4)
                ->all();
            foreach($item as $k => $v){
                //超过预算 去掉
                if($v['budget_total'] < $vat_price+$v['buy_total']){
                    unset($item[$k]);
                }else {

                    $item[$k]['all_budget_total'] = bcdiv($v['budget_total'], 10000, 2);
                    $item[$k]['all_buy_total'] = bcdiv($v['buy_total'], 10000, 2);
                    $item[$k]['buy_total'] = bcdiv($v['buy_total'], 10000, 2);
                    $item[$k]['budget_total'] = bcdiv($v['budget_total'], 10000, 2);

                }

            }

            $ajax = tools::ajax_return('2','成功',$item);
            return $ajax;
        }else{

            //去重
            foreach($atlas_budget as $ka =>  $va){
                if($va['id'] == $item_id['id']){
                    unset($atlas_budget[$ka]);
                }
            }

            $itemArr['left'] = $item_id;
            $itemArr['right'] = $atlas_budget;
            $ajax = tools::ajax_return('1','成功',$itemArr);
            return $ajax;

        }

        $ajax = tools::ajax_return('3','失败',[]);
        return $ajax;


    }



    /*
     *  科目调整报销
     */
    public function actionFeeapply()
    {
        header('Access-Control-Allow-Origin:*');
        $query = new \yii\db\Query();

        $post = Yii::$app->request->post();
        $uid = $post['id'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken($uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('2','token过期,请重新登录',[$checkToken]);
        }


        $tid = $post['tid'];
        $add_id = $post['add_id'];
        $lower_id = $post['lower_id'];
        $price = $post['price'];

        $budget = new \app\models\Budget;
        $addType = $budget->budgetType($add_id);
        $lowerType = $budget->budgetType($lower_id);
        //是否能互相调额
        if($addType['fee_type'] != $lowerType['fee_type']){
            return tools::ajax_return_error('2',$addType['fee_name'].''.$lowerType['fee_name'].'不能调剂',[]);
        }



        //添加 科目调整表
        $create_time = date('Y-m-d H:i:s',time());
        $budAdd = new \app\models\Budget;
        $add = $budAdd->budgetAdd($price,$lower_id,$add_id,$create_time,2);
        if(!$add){
            $ajax = tools::ajax_return_error('1','失败',[1]);
            return $ajax;
        }

        //最新id
        $lastId = Yii::$app->db->getLastInsertId();
        //添加消息列表
        $redis = Yii::$app->cache;
        $accessToken = $redis->get($uid);
        $info = new \app\models\NewInfo;
        $insert = $info->addInfo($uid,$accessToken['realname'],$lastId,3);

        if(!$insert){
            $ajax = tools::ajax_return_error('1','失败',[1]);
            return $ajax;
        }


        //调用model
        $vat = new \app\models\Budget;
        $vat_price = $vat->vatPrice($tid);

        $vatType = $vat->vatType($tid);
        if(!$vatType){
            return tools::ajax_return_error('2','状态修改失败',[1]);
        }

        //修改科目余额
        $updateBudgetPrice = $vat->updateBudgetPrice($add_id,$vat_price,$price);
        if($updateBudgetPrice == 2){
            $ajax = tools::ajax_return_error('1','失败',[2]);
            return $ajax;
        }else if($updateBudgetPrice == 3){
            $ajax = tools::ajax_return_error('2','花费金额超过预算总计',[2]);
            return $ajax;
        }

        //减少科目余额
        $lewBudgetPrice = $vat->lewBudgetPrice($lower_id,$vat_price,$price);
        if($lewBudgetPrice == 2){
            $ajax = tools::ajax_return_error('1','失败',[3]);
            return $ajax;
        }

        $ajax = tools::ajax_return('0');
        return $ajax;




    }









}